package com.placement.refresh.util;

import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Insert the type's description here.
 * Creation date: (2/8/02 11:28:23 AM)
 * @author: fund/Eugene Backlin
 */
public class MailController extends StringUtilities implements Serializable {
    private static final Log logger = LogFactory.getLog(MailController.class);
    
	//
	//
	////////////////////////////
	//
	// Global Variables
	//
	////////////////////////////
	//
	//
	public static String _DEFAULT_SEND_HOST = "mailhost.cmg.fcnbd.com";
	public static String _DEFAULT_RECEIVE_HOST = "mailhost.cmg.fcnbd.com";
	public static String _DEFAULT_SMTP_HOST_KEY = "mail.smtp.host";
	public java.lang.String _from;
	public java.lang.String _to;
	public java.lang.String _sendHost;
	public java.lang.String _receiveHost;
	public java.util.Properties _properties;
	public javax.mail.Session _session;
	public javax.mail.internet.MimeMessage _sendMessage;
	public javax.mail.Store _store;
	public java.lang.String _username;
	public java.lang.String _password;
	public java.lang.String _bodyText;
	//
	////////////////////////////
	// constructors
	////////////////////////////
	//
	/**
	 * MailController constructor comment.
	 */
	public MailController() {
		super();
		init();
	}
	/**
	 * MailController constructor comment.
	 * Creation date: (2/8/02 12:44:36 PM)
	 * @param to java.lang.String
	 * @param from java.lang.String
	 * @param subject java.lang.String
	 */
	public MailController(String to, String from, String subject) {
		super();
		init();
		setTo(to);
		setFrom(from);
		setSubject(subject);
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 3:08:58 PM)
	 */
	public void displayMailMessages() {
		String message[] = getMailMessages();
		logger.debug("*************************************");
		for (int i = 0, n = message.length; i < n; i++) {
			logger.debug(message[i]);
		}
		logger.debug("*************************************");
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (8/29/02 2:59:25 PM)
	 * @return java.lang.String
	 */
	public java.lang.String getBodyText() {
		return _bodyText;
	}
	//
	////////////////////////////
	// accessor methods
	////////////////////////////
	//
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 11:31:48 AM)
	 * @return java.lang.String
	 */
	public java.lang.String getFrom() {
		return _from;
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 11:31:10 AM)
	 * @return java.lang.String
	 */
	public java.lang.String getHost() {
		return getSendHost();
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 3:11:18 PM)
	 * @return javax.mail.Message[]
	 */
	public String[] getMailMessages() {
		ArrayList list = new ArrayList();
		try {
			getStore().connect(getReceiveHost(), getUsername(), getPassword());
			// Get folder
			Folder folder = getStore().getFolder("INBOX");
			folder.open(Folder.READ_ONLY);

			Message message[] = folder.getMessages();
			if (message != null) {
				logger.debug(
					"Retrieving " + message.length + " messages...");

				for (int i = 0, n = message.length; i < n; i++) {
					String msg =
						i
							+ ": "
							+ message[i].getFrom()[0]
							+ " - [ "
							+ message[i].getSubject()
							+ " ]";
					list.add(msg);
				}
				logger.debug("done.");
			} else {
				logger.debug("Retrieving no messages...");
			}

			folder.close(false);
			getStore().close();
		} catch (MessagingException e) {
			logger.debug("getMessageToReply() error: " + e.getMessage());
		}
		return (String[]) (list.toArray(new String[0]));
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 2:50:46 PM)
	 * @return java.lang.String
	 */
	public java.lang.String getPassword() {
		return _password;
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 11:39:26 AM)
	 * @return java.util.Properties
	 */
	public java.util.Properties getProperties() {
		return _properties;
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 11:36:22 AM)
	 * @return java.lang.String
	 */
	public java.lang.String getReceiveHost() {
		return _receiveHost;
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 11:35:44 AM)
	 * @return java.lang.String
	 */
	public java.lang.String getSendHost() {
		return _sendHost;
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 11:46:19 AM)
	 * @return javax.mail.internet.MimeMessage
	 */
	public javax.mail.internet.MimeMessage getSendMessage() {
		return _sendMessage;
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 11:39:59 AM)
	 * @return javax.mail.Session
	 */
	public javax.mail.Session getSession() {
		return _session;
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 2:43:08 PM)
	 * @return javax.mail.Store
	 */
	public javax.mail.Store getStore() {
		return _store;
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 11:32:22 AM)
	 * @return java.lang.String
	 */
	public java.lang.String getTo() {
		return _to;
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 1:11:21 PM)
	 * @return javax.mail.Address[]
	 * @param to java.lang.String
	 */
	public Address[] getToAddresses(String to) {
		String[] toList = stringToArray(to,",");
		ArrayList list = new ArrayList();
		Address[] result = null;

		if (toList != null) {
			for (int i = 0; i < toList.length; i++) {
				try {
					list.add(new InternetAddress(toList[i]));
				} catch (AddressException e) {
					logger.debug(
						"getToAddresses(String to) error: " + e.getMessage());
				}
			}
			result = (Address[]) (list.toArray(new Address[0]));
		}
		return result;
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 2:44:12 PM)
	 * @return java.lang.String
	 */
	public java.lang.String getUsername() {
		return _username;
	}
	//
	////////////////////////////
	// initialization methods
	////////////////////////////
	//
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 11:29:28 AM)
	 */
	public void init() {
		initConnectionDetails();
		initSendMessage(getSession());
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 11:29:15 AM)
	 */
	public void initConnectionDetails() {
		setProperties(System.getProperties());
		setSendHost(_DEFAULT_SEND_HOST);
		setReceiveHost(_DEFAULT_RECEIVE_HOST);
		setSession(Session.getDefaultInstance(getProperties(), null));
		setUsername("carahep");
		setPassword("pjpjpj9");
		try {
			setStore(getSession().getStore("pop3"));
		} catch (NoSuchProviderException e) {
			logger.debug(
				"initConnectionDetails() error: " + e.getMessage());
		}
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 11:49:55 AM)
	 * @param session javax.mail.Session
	 */
	public void initSendMessage(Session session) {
		Date date = new Date();
		String subject =
			"Default Subject from: "
				+ getFrom()
				+ " to: "
				+ getTo()
				+ " sent at: "
				+ date;
		String message =
			"Default Message from: "
				+ getFrom()
				+ " to: "
				+ getTo()
				+ " sent at: "
				+ date;
		setSendMessage(new MimeMessage(session));
		setSubject(subject);
		setBodyText(message);
	}
	//
	////////////////////////////
	// main method
	////////////////////////////
	//
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 12:13:47 PM)
	 * @param args java.lang.String[]
	 */
	public static void main(String[] args) {
		String to1 = "venki.kuppuswamy@jpmorgan.com";
		String to2 =
			"venki.kuppuswamy@jpmorgan.com";
		String from = "venki.kuppuswamy@jpmorgan.com";
		String subject = "This is a test of the MailController send method...";
		String text =
			"If you import the latest com.bankone.cosmos.util (1.0.4 version), ";
		text
			+= "you will see a new MailController. It currently (1.0.4 version) only sends, ";
		text
			+= " [at least from my machine. ;-) ] I am working on the receive part.";
		text += "Enjoy !!! - look at the main() to see how to send. ";
		text
			+= "Please also include the project JavaMail Project from the repository.";

		//
		// This is how to init without any arguments.
		//
		/*
		MailController mc = new MailController();
		mc.setTo(to1);
		mc.setFrom(from);
		mc.setSubject(subject);
		mc.setBodyText(text);
		mc.sendMail();
		*/

		//
		// This is how to init with arguments.
		//

		MailController mc2 = new MailController(to1, from, subject);
		mc2.setBodyText(text);
		try {
			mc2.sendMail();
		} catch (java.lang.Exception e) {
            logger.fatal("main()", e);
		}

		MailController mc3 = new MailController(to1, from, subject);
		mc2.setBodyText(text);
		//
		// This is how to reply with arguments. (in development - replies to message 100)
		//
		/*
		MailController mc2 = new MailController(to2, from, subject);
		mc2.replyMail();
		*/
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 12:10:12 PM)
	 */
	public boolean sendMail() throws Exception {
		boolean iostat = false;

		try {
			setSendMessageAddresses();
			String subject = getSendMessage().getSubject();
			Date date = new Date();
			String msg = getSendMessage().toString();

			Transport.send(getSendMessage());
			logger.debug(
				"Mail: [" + subject + "] was sent at " + date + ".");
			iostat = true;
		} catch (MessagingException e) {
			String msg = "MimeMessage error: " + e.getMessage();
            logger.fatal(msg, e);
			throw new Exception(msg);
		} catch (Exception g) {
			String msg = "Exception error: " + g.getMessage();
            logger.fatal(msg, g);
			throw new Exception(msg);
		}
		return iostat;
	}

	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 12:06:40 PM)
	 * @param text java.lang.String
	 */
	public void setBodyText(String text) {
		_bodyText = text;
		try {
			getSendMessage().setText(text);
		} catch (MessagingException e) {
			logger.debug(
				"setBodyText(String text) error: " + e.getMessage());
		}
	}
	//
	////////////////////////////
	// modifier methods
	////////////////////////////
	//
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 11:31:48 AM)
	 * @param new_from java.lang.String
	 */
	public void setFrom(java.lang.String newFrom) {
		_from = newFrom;
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 11:31:10 AM)
	 * @param new_host java.lang.String
	 */
	public void setHost(java.lang.String newHost) {
		setSendHost(newHost);
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 2:50:46 PM)
	 * @param new_password java.lang.String
	 */
	public void setPassword(java.lang.String newPassword) {
		_password = newPassword;
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 11:39:26 AM)
	 * @param new_properties java.util.Properties
	 */
	public void setProperties(java.util.Properties newProperties) {
		_properties = newProperties;
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 11:36:22 AM)
	 * @param new_receiveHost java.lang.String
	 */
	public void setReceiveHost(java.lang.String newReceiveHost) {
		_receiveHost = newReceiveHost;
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 11:35:44 AM)
	 * @param new_sendHost java.lang.String
	 */
	public void setSendHost(java.lang.String newSendHost) {
		_sendHost = newSendHost;
		getProperties().put(_DEFAULT_SMTP_HOST_KEY, newSendHost);
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 11:46:19 AM)
	 * @param new_sendMessage javax.mail.internet.MimeMessage
	 */
	public void setSendMessage(
		javax.mail.internet.MimeMessage newSendMessage) {
		_sendMessage = newSendMessage;
	}
	//
	////////////////////////////
	// action methods
	////////////////////////////
	//
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 1:39:04 PM)
	 */
	public void setSendMessageAddresses() throws Exception {
		try {
			String from = getFrom();
			String to = getTo();
			String msg = null;
			try {
				if (from == null) {
					msg = "Cannot send mail, the From address is null.";
					throw new Exception(msg);
				}
				if (to == null) {
					msg = "Cannot send mail, the To address is null.";
					throw new Exception(msg);
				}
			} catch (Exception e) {
				throw new Exception(msg);
			}
			getSendMessage().setFrom(new InternetAddress(from));
			Address[] toAddresses = getToAddresses(to);
			if (toAddresses != null) {
				if (toAddresses.length < 2) {
					getSendMessage().addRecipient(
						Message.RecipientType.TO,
						toAddresses[0]);
				} else {
					getSendMessage().addRecipients(
						Message.RecipientType.TO,
						toAddresses);
				}
			}
		} catch (MessagingException e) {
			logger.debug(
				"setSendMessageAddresses() error: " + e.getMessage());
		}
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 11:39:59 AM)
	 * @param new_session javax.mail.Session
	 */
	public void setSession(javax.mail.Session newSession) {
		_session = newSession;
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 2:43:08 PM)
	 * @param new_store javax.mail.Store
	 */
	public void setStore(javax.mail.Store newStore) {
		_store = newStore;
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 11:55:49 AM)
	 * @param message java.lang.String
	 */
	public void setSubject(String subject) {
		try {
			getSendMessage().setSubject(subject);
		} catch (MessagingException e) {
			logger.debug(
				"setSubject(String subject) error: " + e.getMessage());
		}

	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 11:32:22 AM)
	 * @param new_to java.lang.String
	 */
	public void setTo(java.lang.String newTo) {
		_to = newTo;
	}
	/**
	 * Insert the method's description here.
	 * Creation date: (2/8/02 2:44:12 PM)
	 * @param new_username java.lang.String
	 */
	public void setUsername(java.lang.String newUsername) {
		_username = newUsername;
	}
}